package com.mlog.njyjy.ndop.msg.admin.controller;

import com.mlog.njyjy.mp.starter.maws.response.Resp;
import com.mlog.njyjy.ndop.msg.admin.service.FlowManagerService;
import com.mlog.njyjy.ndop.msg.common.domain.Flow;
import com.mlog.njyjy.ndop.msg.common.domain.NodeItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author zyz
 * @version v1.0, 2020/8/11
 */
@Api(value = "消息流程管理")
@RestController
@CrossOrigin
@RequestMapping("/api")
public class MsgFlowController {

    @Autowired
    private FlowManagerService flowManagerService;

    @ApiOperation(value = "列出全部消息流程", tags = "消息流程管理")
    @GetMapping("/msgFlows")
    public Resp listAll() {
        return Resp.of(flowManagerService.list());
    }

    @ApiOperation(value = "保存消息流程", tags = "消息流程管理")
    @PostMapping("/msgFlows")
    public Resp save(@RequestBody Flow flow) {
        Flow existed = flowManagerService.save(flow);
        if (existed != null) {
            return Resp.of(existed);
        }
        return Resp.FAIL;
    }

    @ApiOperation(value = "保存消息流程节点配置", tags = "消息流程管理")
    @PostMapping("/msgFlows/{flowId}/nodes")
    public Resp saveNodesByFlow(@PathVariable Long flowId, @RequestBody List<NodeItem> nodeItems) {
        boolean success = flowManagerService.saveNodes(flowId, nodeItems);
        return success ? Resp.OK : Resp.FAIL;
    }

    @ApiOperation(value = "移除消息流程", tags = "消息流程管理")
    @DeleteMapping("/msgFlows/{id}")
    public Resp remove(@PathVariable Long id) {
        boolean success = flowManagerService.remove(id);
        return success ? Resp.OK : Resp.FAIL;
    }

    @ApiOperation(value = "移除节点", tags = "消息流程管理")
    @DeleteMapping("/msgFlows/{flowId}/nodes")
    public Resp removeNode(@PathVariable Long flowId, @RequestParam Long id) {
        boolean success = flowManagerService.removeNode(id);
        return success ? Resp.OK : Resp.FAIL;
    }

    @ApiOperation(value = "列出消息流程节点", tags = "消息流程管理")
    @GetMapping("/nodes/{id}")
    public Resp listSources(@PathVariable Long id) {

        List<NodeItem> nodeItemList = flowManagerService.findByFlow(id);
        if (nodeItemList != null) {
            return Resp.of(nodeItemList);
        }
        return Resp.FAIL;
    }


    @ApiOperation(value = "导入配置文件", tags = "消息流程管理")
    @PostMapping(value = "/flows/import")
    public Resp importFlow(MultipartFile file) {
        try {
            return Resp.of(flowManagerService.importFlow(file.getBytes()));
        } catch (IOException e) {
            return Resp.fail(e.getLocalizedMessage());
        }
    }


}
